#!/usr/bin/env python
#!-*-coding:utf-8 -*-

from diagExcept import DiagArgsTypeExept
import binascii

#press key

#cmd
DIAG_ASBSIM_F = '62' #ASBSIM工具新增功能

DIAG_ASBSIM_FLAG = 4

#sub cmd
# DIAG_HEADER_LENGTH = 8  #DIAG协议头长度为8
DIAG_HEADER_LENGTH = 4  #数据区间的头长度为4

DIAG_ASBSIM_SUB_FLAG = '02'   #ASBSIM工具新增功能

class Type:
    # type
    TYPE_NEED_HEAD_IN_DATA_AREA = 0
    TYPE_NONE_HEAD_IN_DATA_AREA = 1

class DiagCommand(object):
    def __init__(self):
        pass

    def __set_diag_SN(self):
        return '00 00 00 00'

    def __get_diag_leng(self, diag_data):
        """
        根据diag协议中数据区域的数据，返回一个十六进制的字符串，表示整个协议的长度
        :param diag_data:diag协议中数据区域的数据，String类型
        :return:String
        """
        if not isinstance(diag_data, (str, unicode)):
            raise DiagArgsTypeExept()

        diag_data_len = len(diag_data.replace(" ", ""))/2

        diag_len_str = str(hex(DIAG_HEADER_LENGTH+diag_data_len))[2:]

        len_str = ''
        if len(diag_len_str) == 1:
            len_str = "0"+diag_len_str + ' 00'
        elif len(diag_len_str) == 2:
            len_str = diag_len_str + ' 00'
        elif len(diag_len_str) == 3:
            len_1 = "0"+diag_len_str[0]
            len_2 = diag_len_str[1:]
            if int(len_1,16) > len(len_2):
                len_str = len_1 + " " + len_2
            else:
                len_str = len_2 + " " + len_1
        else:
            len_1 = diag_len_str[0:2]
            len_2 = diag_len_str[2:]
            if int(len_1, 16) > len(len_2):
                len_str = len_1 + " " + len_2
            else:
                len_str = len_2 + " " + len_1
        return len_str

    def __mySplit1(self, str):
        """
        分割字符串为数组
        :return:
        """
        t = []
        for i in range(len(str)/2):
            t.append(int(str[2 * i:2 * (i + 1)], 16))
        return t

    def __handle_special(self, one_frame):
        """
        处理数据帧中特殊的数值，0x7E，0x7D
        :param one_frame: 一帧数据
        :return:
        """
        # TODO, 对于数据帧中含有0x7D的需要转化
        new_one_frame = ""
        one_frame = one_frame.replace(" ", "")
        for x in xrange(2, len(one_frame)+2, 2):
            sp = one_frame[x - 2:x]
            if sp.upper() == "7E":
                new_one_frame += "7D5E"
            elif sp.upper() == "7D":
                new_one_frame += "7D5D"
            else:
                new_one_frame += sp
        return new_one_frame

    def __assembly_diag(self, cmd, type):
        """
        组装diag命令
        :param cmd: 十六进制的字符串
        :param diag_cmd_type: diag协议的类型，是AT命令还是按键命令
        :return:
        """
        diag_data = ""
        diag_ap_cmd = "20 00"
        diag_length = self.__get_diag_leng(cmd)
        if type == Type.TYPE_NEED_HEAD_IN_DATA_AREA:
            diag_data = (diag_ap_cmd + diag_length)

        #TODO   1、协议的构造；2、7E的校验

        diag_data += cmd.replace(" ", "")
        diag_ = self.__handle_special(diag_data)

        # return binascii.unhexlify(diag_)
        return self.__mySplit1(diag_)


    def getASBSIMCommand(self, cmd, type = Type.TYPE_NEED_HEAD_IN_DATA_AREA):
        """
            1、该函数对外提供
            2、参数为ASBSIM工具新增的字符串
            3、返回一个diag协议的字符串，十六进制
            :param cmd:
            :return:
            """
        if not isinstance(cmd, (str, unicode)):
            raise Exception("cmd of getASBSIMCommand function must is string!")

        ASBSIMcmdHex = binascii.hexlify(cmd)
        return self.__assembly_diag(ASBSIMcmdHex, type)

    def getTpCommand(self):
        return binascii.unhexlify("7E 00 00 00 00 10 00 22 00 01 00 64 00 14 00 14 00 7E".replace(" ",""))